package com.example.tcp.server;

import com.example.WebSocketMessageDecoder;
import com.example.WebSocketMessageEncoder;
import com.example.codec.BootstrapConfig;
import com.example.common.constant.ConsoleColors;
import com.example.tcp.handler.NettyServerHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.stream.ChunkedWriteHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class LimWebSocketServer {

    private final static Logger logger= LoggerFactory.getLogger(LimWebSocketServer.class);

    BootstrapConfig.TcpConfig config;
    EventLoopGroup mainGroup;
    EventLoopGroup subGroup;
    ServerBootstrap server;

    //这边准备接入webrtc  用于进行语聊房
    public LimWebSocketServer(BootstrapConfig.TcpConfig config){
        this.config=config;
        mainGroup = new NioEventLoopGroup(1); //线程池
        subGroup = new NioEventLoopGroup();//
        server=new ServerBootstrap();
        server.group(mainGroup,subGroup)
                .channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG,1024)
                .option(ChannelOption.SO_REUSEADDR,true)
                .childOption(ChannelOption.TCP_NODELAY,true)
                .childOption(ChannelOption.SO_KEEPALIVE,true)
                .childHandler(new ChannelInitializer<SocketChannel>(){
                    @Override
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        ChannelPipeline pipeline=socketChannel.pipeline();
                        pipeline.addLast("http-codec",new HttpServerCodec());
                        pipeline.addLast("http-chunked",new ChunkedWriteHandler());
                        pipeline.addLast("aggregator",new HttpObjectAggregator(65535));
                        pipeline.addLast(new WebSocketServerProtocolHandler("/ws"));
                        pipeline.addLast(new WebSocketMessageDecoder());
                        pipeline.addLast(new WebSocketMessageEncoder());
                        pipeline.addLast(new NettyServerHandler(config.getBrokerId(),config.getLogicUrl()));   //添加Netty  这样NettyServerHandler 才会处理websocket的消息
                    }
                });
    }

    public void start(){
        this.server.bind(this.config.getWebSocketPort());
        logger.info(ConsoleColors.GREEN+"websocket start"+ConsoleColors.RESET);
    }
}
